package com.productline;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.apple.util.PLEConfigure;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class GeneratorFrame extends JFrame {

	public static HashMap<JTextField, Element> map = new HashMap<JTextField, Element>();

	public static Document doc;
	public static PicturePanel picture = new PicturePanel();
	public static SensorConfigurePanel generatorPanel;

	public GeneratorFrame() {

		this.setLayout(null);
		// show the picture of the FWS
		// PicturePanel picture = new PicturePanel();
		picture.setBounds(0, 0, 400, 430);
		// do the configuration
		JPanel configuration = new JPanel(null);
		configuration.setBounds(400, 0, 400, 800);

		// sensor configuration panel, sub panel of configuration
		doc = readFromFile();
		generatorPanel = new SensorConfigurePanel(doc);
		generatorPanel.setBounds(0, 0, 400, 200);

		// choose which kind of sensor to be configured
		JPanel sp = new JPanel();

		// ButtonGroup g = new ButtonGroup();
		// int x = 200, y = 0;
		// int times = 0;
		// wind 270,150
		// air 25,100
		// sea 140,250
		// position 100,50
		int[][] picturePosition = { { 270, 25, 140, 100 },
				{ 150, 100, 250, 50 } };
		int i = 0;
		for (Object e : doc.getRootElement().getChild("sensors").getChildren()) {
			String name = ((Element) e).getChildText("name");
			JCheckBox b = new JCheckBox(name, false);
			// g.add(b);
			sp.add(b);

			b.addActionListener(new SensorActionListener(name,
					picturePosition[0][i], picturePosition[1][i], ((Element) e)
							.getChildText("ifSelected"), picture,
					generatorPanel));

			i++;
		}

		Element e = doc.getRootElement().getChild("position-sensor");// .
																		// getChildren
																		// ();
		if (e != null) {
			String name = ((Element) e).getChildText("name");
			JCheckBox b = new JCheckBox(name, false);
			// g.add(b);
			sp.add(b);
			b.addActionListener(new SensorActionListener(name,
					picturePosition[0][i], picturePosition[1][i], ((Element) e)
							.getChildText("ifSelected"), picture,
					generatorPanel));

		}

		sp.setBounds(0, 430, 400, 100);
		this.add(sp);

		// FWS configuration panel, sub panel of configuration
		JPanel configurePanel = new JPanel(null);
		configurePanel.setBounds(0, 200, 400, 150);

		JLabel transmitPeriodLabel = new JLabel("Transmit Period: ");
		JTextField transmitPeriodText = new JTextField();
		transmitPeriodText.setText(doc.getRootElement().getChild(
				"transmitPeriod").getText());
		configurePanel.add(transmitPeriodLabel);
		transmitPeriodLabel.setBounds(0, 10, 100, 25);
		configurePanel.add(transmitPeriodText);
		transmitPeriodText.setBounds(100, 10, 200, 25);
		transmitPeriodText.addFocusListener(new MyFocusListener(
				transmitPeriodText, "transmitterPeriod"));

		// JLabel historyLabel = new JLabel("History: ");
		// JTextField historyText = new JTextField();
		//historyText.setText(doc.getRootElement().getChild("history").getText()
		// );
		// configurePanel.add(historyLabel);
		// historyLabel.setBounds(0, 35, 100, 25);
		// configurePanel.add(historyText);
		// historyText.setBounds(100, 35, 200, 25);
		// historyText.addFocusListener(
		// new MyFocusListener(
		// historyText,doc.getRootElement().getChild("history")));

		JPanel msgFormatPanel = new JPanel();
		Border msgBorder = BorderFactory.createTitledBorder("Message Format: ");
		msgFormatPanel.setBorder(msgBorder);
		ButtonGroup group = new ButtonGroup();
		JRadioButton shortButton = new JRadioButton("SHORT", false);
		group.add(shortButton);
		JRadioButton longButton = new JRadioButton("LONG", false);
		group.add(longButton);
		if (doc.getRootElement().getChildText("messageFormat").equals("short"))
			shortButton.setSelected(true);
		else
			longButton.setSelected(true);

		shortButton.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				if (doc.getRootElement().getChildText("messageFormat").equals(
						"short"))
					doc.getRootElement().getChild("messageFormat").setText(
							"long");
				else
					doc.getRootElement().getChild("messageFormat").setText(
							"short");

			}

		});
		msgFormatPanel.add(shortButton);
		msgFormatPanel.add(longButton);
		msgFormatPanel.setBounds(0, 60, 400, 60);
		configurePanel.add(msgFormatPanel);

		// generate button, sub panel of configuration
		JPanel controlPanel = new JPanel();
		controlPanel.setBounds(0, 350, 400, 100);
		JButton saveButton = new JButton("Generate My FWS, please...");

		saveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				GeneratorFrame.generateFWS(doc);

			}
		});
		saveButton.setSize(150, 40);
		controlPanel.add(saveButton);

		// JButton button = new JButton("Generate");
		//		
		// button.addActionListener(new ActionListener(){
		// public void actionPerformed(ActionEvent arg0) {
		// GeneratorFrame.writeToFile(doc);
		// Generator.generate(doc);
		// }
		// });
		// button.setSize(150,40);
		// controlPanel.add(button);

		configuration.add(generatorPanel);
		configuration.add(configurePanel);
		configuration.add(controlPanel);

		add(picture);
		add(configuration);

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(800, 600);
	}

	public static Document readFromFile() {
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = null;
		try {
			doc = builder.build(new File(".\\Generator\\sensor.xml"));
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}

	public static void generateFWS(Document doc) {
		
		JFileChooser jfc = new JFileChooser();
		jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		jfc.setDialogTitle("Select the target folder for generated source code(select an empty folder)...");
		jfc.showSaveDialog(null);
		File selectedFile = jfc.getSelectedFile();
		if(selectedFile==null){
			return;
		}
		String targetPath = selectedFile.getAbsolutePath()+java.io.File.separator;
		
		PLEConfigure con = PLEConfigure.instance();
		try {
			// store configuration information into apple.properties file.
			// this file will be used by the generated program
			con.store(new FileOutputStream("apple.properties"),
					"apple.properties");			
			// generate the souce code of the product according to user's
			// requirement
			new SrcGenerator(PLEConfigure.instance(), targetPath).generateSrc();


		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
